package co.th.bjc.md.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import co.th.bjc.md.dao.Images;
import co.th.bjc.md.process.service.CallService;
import co.th.bjc.md.service.interfaces.ProductManageService;

import net.sf.json.JSONArray;
import co.th.bjc.md.dao.Product;
import co.th.bjc.md.dao.Supplier;
import co.th.bjc.md.helper.utils.ThaiUtil;

/**
 * Servlet implementation class ProductManageServlet
 */
public class ProductManageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProductManageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html; charset=UTF-8");
		JSONArray jsonObject = new JSONArray();
		boolean status = false;
		String action = request.getParameter("action")==null?"":request.getParameter("action");
		
		if(action.equals("SEARCH")){
			PrintWriter out = response.getWriter();
			jsonObject = this.getSearchResult(request, response);
			out.print(jsonObject);
		}else if(action.equals("DELETE")){
			// Delete process
			if(this.delete(request, response)){
				PrintWriter out = response.getWriter();
				status = true;
				jsonObject = this.getSearchResult(request, response);
				jsonObject.add(status);
				out.print(jsonObject);
			}
		}else if(action.equals("GETEDIT")){
			PrintWriter out = response.getWriter();
			jsonObject = getEditItem(request, response);
			status = true;
			jsonObject.add(status);
			out.print(jsonObject);
		}else if(action.equals("GETIMG")){
			getBlob(request, response);
		}else if(action.equals("GETSUPPLIER")){
			PrintWriter out = response.getWriter();
			jsonObject = getSupplierList();
			out.print(jsonObject);
		}else if(action.equals("DELETEIMG")){
			boolean deleteImgStatus = deleteImg(Integer.parseInt(request.getParameter("imageId")));
			jsonObject = JSONArray.fromObject(deleteImgStatus);
			PrintWriter out = response.getWriter();
			out.print(jsonObject);
		}else{
			getServletContext().getRequestDispatcher("/jsp/datamanage/manage_product_main.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		JSONArray jsonObject = new JSONArray();
		boolean status = false;
		try {
	        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
	        for (FileItem item : items) {
	            if (item.isFormField()) {
	                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
	            	String fieldname = item.getFieldName();
	            	String fieldValue = item.getString();
	            	if(fieldname.equals("action")){
	            		if(fieldValue.equals("INSERT")){
	            			// Insert process
	            			if(this.insert(items)){
	            				status = true;
	            				jsonObject = this.getSearchResult(request, response);
	            				jsonObject.add(status);
	            				out.print(jsonObject);
	            			}
	            		}else if(fieldValue.equals("EDIT")){
	            			// Update process
	            			if(this.update(items)){
	            				status = true;
	            				jsonObject = this.getSearchResult(request, response);
	            				jsonObject.add(status);
	            				out.print(jsonObject);
	            			}
	            		}
	            		break;
	            	}
	            }
	        }
	    }  catch (FileUploadException e) {
	        e.printStackTrace();
	    }
		
		
	}
	
	private JSONArray getSupplierList(){
		ProductManageService prodService = (ProductManageService) CallService.getService("productmanage");
		List<Supplier> supplierList = prodService.getAllSupplier();
		JSONArray json = JSONArray.fromObject(supplierList); 
		return json;
	}
	
	private boolean insert(List<FileItem> items) {
		boolean status = false;
		String createBy = "";
		String productCode = "";
		Product prod = new Product();
		List<Images> listImg = new ArrayList<Images>();
		try {
	        for (FileItem item : items) {
	            if (item.isFormField()) {
	                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
	                String fieldname = item.getFieldName();
	                String fieldvalue = item.getString();
	                if(fieldname.equals("user_code")){
	                	createBy = fieldvalue;
	                }else if(fieldname.equals("ins_product_code")){
	                	productCode = fieldvalue;
	                	prod.setProductCode(BigDecimal.valueOf(Long.parseLong(fieldvalue)));
	                }else if(fieldname.equals("ins_product_name")){
	                	prod.setProductName(fieldvalue);
	                }else if(fieldname.equals("ins_product_detail")){
	                	prod.setProductDetail(fieldvalue);
	                }else if(fieldname.equals("ins_active")){
	                	prod.setActive(fieldvalue);
	                }else if(fieldname.equals("ins_supplier_code")){
	                	prod.setSupplierCode(BigDecimal.valueOf(Long.parseLong(fieldvalue)));
	                }
	            } else {
	                // Process form file field (input type="file").
	                String filename = FilenameUtils.getName(item.getName());
	                if(!filename.equals("")){
						InputStream filecontent = item.getInputStream();
						Images img = new Images();
						img.setCreateDate(new Date());
						img.setUpdateDate(new Date());
						img.setImageName(filename);
						img.setImageData(filecontent);
						listImg.add(img);
	                }
	            }
	        }
	        int imgSize = listImg.size();
	        for (int i = 0; i < imgSize; i++) {
	        	listImg.get(i).setCreateBy(createBy);
	        	listImg.get(i).setUpdateBy(createBy);
	        	listImg.get(i).setProductCode(BigDecimal.valueOf(Long.parseLong(productCode)));
	        }
	        prod.setImages(listImg);
	        prod.setCreateDate(new Date());
	        prod.setUpdateBy(createBy);
	        prod.setUpdateDate(new Date());
	        ProductManageService prodService = (ProductManageService) CallService.getService("productmanage");
	        status = prodService.addProduct(prod);
	        
	    }  catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return status;
	}
	
	private boolean update(List<FileItem> items) {
		String[] imgId = new String[4];
		int index = 0;
		boolean status = false;
		String createBy = "";
		String productCode = "";
		Product prod = new Product();
		List<Images> listImg = new ArrayList<Images>();
		try {
	        for (FileItem item : items) {
	            if (item.isFormField()) {
	                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
	                String fieldname = item.getFieldName();
	                String fieldvalue = item.getString();
	                if(fieldname.equals("user_code")){
	                	createBy = fieldvalue;
	                }else if(fieldname.equals("ins_product_code")){
	                	productCode = fieldvalue;
	                	prod.setProductCode(BigDecimal.valueOf(Long.parseLong(fieldvalue)));
	                }else if(fieldname.equals("ins_product_name")){
	                	prod.setProductName(fieldvalue);
	                }else if(fieldname.equals("ins_product_detail")){
	                	prod.setProductDetail(fieldvalue);
	                }else if(fieldname.equals("ins_active")){
	                	prod.setActive(fieldvalue);
	                }else if(fieldname.equals("ins_supplier_code")){
	                	prod.setSupplierCode(BigDecimal.valueOf(Long.parseLong(fieldvalue)));
	                }else if(fieldname.equals("ins_product_img[]")){
	                	listImg.add(null);
	                }else if(fieldname.equals("ins_product_img_id[]")){
	                	imgId[index] = fieldvalue;
	                	index++;
	                }
	            } else {
	                // Process form file field (input type="file").
	                String filename = FilenameUtils.getName(item.getName());
//	                if(!filename.equals("")){
						InputStream filecontent = item.getInputStream();
						Images img = new Images();
						img.setCreateDate(new Date());
						img.setUpdateDate(new Date());
						img.setImageName(filename);
						img.setImageData(filecontent);
						listImg.add(img);
//	                }
	            }
	        }
	        int imgSize = listImg.size();
	        for (int i = 0; i < imgSize; i++) {
	        	if(listImg.get(i) != null){
		        	if(!imgId[i].equals("")){
		        		listImg.get(i).setImageId(Integer.parseInt(imgId[i]));
		        	}
		        	
		        	listImg.get(i).setCreateBy(createBy);
		        	listImg.get(i).setUpdateBy(createBy);
		        	listImg.get(i).setProductCode(BigDecimal.valueOf(Long.parseLong(productCode)));
	        	}
	        }
	        listImg.removeAll(java.util.Collections.singleton(null));
	        prod.setImages(listImg);
	        prod.setCreateDate(new Date());
	        prod.setUpdateBy(createBy);
	        prod.setUpdateDate(new Date());
	        ProductManageService prodService = (ProductManageService) CallService.getService("productmanage");
	        status = prodService.editProduct(prod);
	        
	    }  catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return status;
	}
	
	private boolean delete(HttpServletRequest request, HttpServletResponse response) {
		BigDecimal id = BigDecimal.valueOf(Long.parseLong(request.getParameter("productId")));
		ProductManageService prod = (ProductManageService) CallService.getService("productmanage");
		boolean status = prod.removeProduct(id);
		return status;
	}
	
	private JSONArray getEditItem(HttpServletRequest request, HttpServletResponse response){
		
		BigDecimal id = BigDecimal.valueOf(Long.parseLong(request.getParameter("productId")));
		ProductManageService prod = (ProductManageService) CallService.getService("productmanage");	
		Product pro = prod.getEditProduct(id);
		JSONArray jsonObject = JSONArray.fromObject(pro);
		return jsonObject;
	}
	
	private JSONArray getSearchResult(HttpServletRequest request, HttpServletResponse response) {
		ProductManageService prod = (ProductManageService) CallService.getService("productmanage");
		String productName = request.getParameter("srh_product_name") == null?"":request.getParameter("srh_product_name");
		String supplierCode = request.getParameter("srh_supplier_code") == null || request.getParameter("srh_supplier_code").equals("")?"0":request.getParameter("srh_supplier_code");
		List<Product> list = prod.getAllProduct(productName, BigDecimal.valueOf(Long.parseLong(supplierCode)));
		JSONArray jsonObject = JSONArray.fromObject(list);
		return jsonObject;
	}

	private void getBlob(HttpServletRequest request, HttpServletResponse response) throws IOException{
		ProductManageService prod = (ProductManageService) CallService.getService("productmanage");
		InputStream in = prod.getImgBlob(Integer.parseInt(request.getParameter("imageId")));
		byte[] bytes = IOUtils.toByteArray(in);
	    response.setContentType("image/jpeg");
	    OutputStream outputStream = response.getOutputStream();
	    outputStream.write(bytes);
	    outputStream.flush();
	    outputStream.close();
	}
	
	private boolean deleteImg(int id){
		boolean status = false;
		ProductManageService prod = (ProductManageService) CallService.getService("productmanage");
		status = prod.removeImage(id);
		return status;
	}
}
